var cpt = require("crypto");
var mongoose = require("mongoose");

var MongoDB = require("./MongoDB");
var Schemas = require("./Schemas");

var logger = new require("../log/Logger")("LogItemDao");

var LogItemDao = function(appName, collectionName) {
    var LogItemModel = MongoDB.getMongoose().model('LogItemModel', Schemas.LogItemSchema, collectionName);

    this.saveLog = function(modelData) {
        if (MongoDB.isInited()) {
            logger.info(modelData);
            var dateTime = new Date(modelData.timeStr);
            var md5Cpt = cpt.createHash("md5");

            var contentMD5 = md5Cpt.update(modelData.levelStr + modelData.moduleName + modelData.content).digest("hex");

            var conditions = {
                md5: contentMD5
            };

            var update = {
                $setOnInsert: {
                    md5: contentMD5,
                    dateTime: dateTime,
                    level: levelStringToLevel(modelData.levelStr),
                    module: modelData.moduleName,
                    body: modelData.content
                },
                $push: {
                    more: dateTime
                }
            };

            var options = {
                upsert: true
            };

            return new Promise(function(reslove, reject){
                LogItemModel.update(conditions, update, options, function(error) {
                    if (!error) {
                        reslove();
                    } else {
                        reject();
                        logger.error(error);
                    }
                });
            });
        } else {
            logger.error("database is not prepared!");
        }
    }

    this.getAppNameList = function() {

    }

    this.getModuleList = function() {

    }

    this.getLogList = function() {

    }
}

function levelStringToLevel(levelStr) {
    switch (levelStr.toLowerCase()) {
        case "verb":
            return 0;
        case "info":
            return 1;
        case "debug":
            return 2;
        case "warning":
            return 3;
        case "error":
            return 4;
        default:
            return 5;
    }
}

module.exports = LogItemDao;
